<script setup>
import { saveQuestion, getAliyunConfig } from '@/api/my';
import { Crypto } from '@/utils/Crypto';
import { encode, decode } from '@/utils/base64';

//响应式变量
const files = ref([]);
const aliconfig = ref(null);
const timeout = ref(87600); // 上传超时时间
const style = ref(null);
const orderId = ref(0);
const deviceId = ref(0);
const deviceUuid = ref(0);
const style1 = ref('');
const style2 = ref('');
const textLength = ref(0);

// 初始化表单数据
const formData = reactive({
  phone: '',
  introduction: ''
});

//表单校验
const formSubmit = async () => {
  //问题校验
  const question = formData.introduction || '';
  if (question.length <= 5) {
    uni.showToast({
      title: '请检查你的问题描述,不能为空且大于5个字',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  
// 输入手机号表单校验
  const contact = formData.phone;
  if (!/^1[34578]\d{9}$/.test(contact) || contact.length == 0) {
    uni.showToast({
      title: '请检查联系电话是否错误',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  const data = {
    deviceId: deviceId.value,
    deviceUuid: deviceUuid.value,
    contact: Number(contact),
    question: question,
    images: files.value,
    orderId: orderId.value
  };

  try {
    await saveQuestion(data);
    uni.showToast({
      title: '感谢您的反馈',
      icon: 'success',
      duration: 2000
    });

    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/my/my'
      });
    }, 2000);
  } catch (error) {
    console.error(error);
  }
};

//字数限制
const textareaChange = (e) => {
  textLength.value = e.detail.value.length;
};

//选择图片并上传成功
const chooseImage = (e) => {
  console.log('上传成功',e);
  const fileslist = e.tempFilePaths;
  console.log('fileslist',fileslist);
  fileslist.forEach((item) => {
    console.log('item',item);
    const tempFilePaths = item;
    const da = new Date();
    const time = da.getTime();
    const fileTypeIndex = tempFilePaths.lastIndexOf('.');
    const fileType = tempFilePaths.substring(fileTypeIndex);
    const aliyunFileKey = 'wechatMini' + tempFilePaths.substring(10, 19) + decode(time) + '/' + new Date().getTime() + Math.floor(Math.random() * 150) + fileType;
    console.log('aliyunFileKey', aliyunFileKey);
    const aliyunServerURL = `https://${aliconfig.value.ossBucket}.oss-${aliconfig.value.ossRegionId}.aliyuncs.com/`;
    const policyBase64 = getPolicyBase64();
    const signature = getSignature(policyBase64);

    uni.uploadFile({
      url: aliyunServerURL,
      filePath: tempFilePaths,
      name: 'file',
      formData: {
        key: aliyunFileKey,
        policy: policyBase64,
        OSSAccessKeyId: aliconfig.value.accessKeyId,
        signature: signature,
        success_action_status: '200'
      },
      success: (uploadRes) => {
        if (uploadRes.statusCode !== 200) {
          uni.showToast({
            title: '上传错误',
            icon: 'none'
          });
          return;
        }
        files.value.push(aliyunServerURL + aliyunFileKey);
        if (files.value.length >= 4) {
          style.value = 'display: none';
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    });
  });
};

// getPolicyBase64 方法生成一个上传策略的 Base64 编码字符串
const getPolicyBase64 = () => {
  let date = new Date();
  date.setHours(date.getHours() + timeout.value);
  const policyText = {
    expiration: date.toISOString(),
    conditions: [['content-length-range', 0, 5 * 1024 * 1024]]
  };
  return encode(JSON.stringify(policyText));
};

// getSignature方法则使用该 Base64 编码字符串生成签名
const getSignature = (policyBase64) => {
  console.log('getSignature',getSignature);
  const accesskey = aliconfig.value.accessKeySecret;
  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  return Crypto.util.bytesToBase64(bytes);
};

//预览照片
const previewImageis = (e) => {
  console.log('e',e);
  // 检查点击的元素是否是上传按钮
  if (e.target && e.target.tagName && e.target.tagName.toLowerCase() !== 'uni-file-picker') {
    uni.previewImage({
      current: e.currentTarget.id,
      urls: files.value
    });
  }
};

//删除图片
const deleteImage = (e) => {
  console.log(e);
  const index = e.index; // 获取当前长按图片下标

  files.value.splice(index, 1);
  uni.showModal({
  	title: '系统提醒',
  	content: '确定要删除此图片吗？',
  	success: (res) => {
  		if (res.confirm) {
  			files.value.splice(index, 1);
  		}
  	}
  });
};


/**
 * 生命周期函数--监听页面加载
 */
onLoad(async (options) => {
  console.log(options);
  if (options.orderId) {
    orderId.value = Number(options.orderId);
  }
  if (options.deviceId) {
    deviceId.value = Number(options.deviceId);
    style1.value = 'display: none';
  } else {
    style2.value = 'display: none';
  }
  if (options.deviceUuid) {
    deviceUuid.value = Number(options.deviceUuid);
  }
  try {
    const response = await getAliyunConfig();
    aliconfig.value = response.data;
  } catch (error) {
    console.error(error);
  }
});
</script>

<template>
  <view class="header_failure">
    <view class="fankuitext">感谢你的反馈!</view>
    <view class="equipment">
      <view class="equipment_SN">
        <view class="text_SN">设备SN号</view>
        <text class="text_Number">{{ deviceId }}</text>
      </view>
      <view class="equipment_IMEI">
        <view class="text_SN">设备IMEI</view>
        <text class="text_Number">{{ deviceUuid }}</text>
      </view>
    </view>
    <form @submit.prevent="formSubmit">
      <view class="phoneNumber">
        <uni-forms :modelValue="formData" label-position="top">
          <uni-forms-item label="联系电话" required>
            <input class="custom_input" v-model="formData.phone" placeholder="请输入联系电话" placeholder-class="phsy" />
          </uni-forms-item>
          <uni-forms-item label="问题描述" required>
            <textarea
              class="custom_textarea"
              type="textarea"
              v-model="formData.introduction"
              @input="textareaChange"
              placeholder="(至少五个字)请详细描述您遇到的问题,我们会尽快处理,感谢你的反馈!"
              placeholder-class="phsy"
            />
            <view class="problemBottom">
              <text>{{ textLength }}/200</text>
            </view>
          </uni-forms-item>
        </uni-forms>
      </view>
      <view class="Upload">
        <uni-section title="上传故障图片">
          <view class="example_body"  @tap="previewImageis">
            <uni-file-picker limit="4" title="最多选择4张图片" @select="chooseImage" @delete="deleteImage"></uni-file-picker>
          </view>
        </uni-section>
      </view>
      <button class="submit" form-type="submit">提交</button>
    </form>
  </view>
</template>

<style lang="scss">
// 页面样式
$light-color: #ececec;

page {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
}

.is-input-border {
  border-radius: 10rpx !important;
  background-color: $light-color !important;
}

.custom_input {
  margin: 0 auto;
  width: 90%;
  height: 100rpx;
  background-color: #ececec;
}

.custom_textarea {
  width: 90%;
  margin: 0 auto;
  background-color: #ececec;
}

.uni-forms-item__label {
  width: 100px !important;
  padding-left: 50rpx !important;
  box-sizing: content-box !important;
  font-size: 36rpx !important;
  color: #000 !important;
}

.uni-section-header {
  padding: 6px 0 !important;
}

.icon-add {
  background-color: #ccc !important;
}

.file-title,
.file-count,
.uni-section__content-title {
  font-size: 30rpx !important;
}

.file-count {
  padding-right: 40rpx !important;
}

.phsy {
  font-size: 30rpx !important;
  color: #999 !important;
}

.header_failure {
  height: 180rpx;
  width: 750rpx;
  background-color: #fff;

  .fankuitext {
    margin-top: 20rpx;
    padding-left: 40rpx;
    font-size: 40rpx;
    font-weight: bold;
  }

  .equipment {
    display: flex;
    justify-content: space-around;
    margin-top: 30rpx;
    width: 750rpx;
    border-top: 1px solid $light-color;

    .equipment_SN,
    .equipment_IMEI {
      padding-top: 20rpx;
      display: flex;
      flex-direction: column;
    }

    .text_SN,
    .text_Number {
      font-size: 34rpx;
      color: #333;
      text-align: center;
    }
  }

  .phoneNumber {
    padding-top: 30rpx;

    .problemBottom {
      margin: 0 auto;
      width: 90%;
      background-color: #ececec;
      border-radius: 0 0 10rpx 10rpx;
      text-align: right;
    }
  }

  .Upload {
    padding-left: 50rpx;
  }

  .submit {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 40rpx;
    width: 600rpx;
    height: 100rpx;
    color: #fff;
    background: #2185f5;
    border-radius: 20rpx;
  }
}
</style>
